'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { IconUser, IconMail, IconShield, IconSettings, IconEdit, IconTrash, IconLock, IconCheck, IconX } from "@tabler/icons-react"
import useAuthStore from '@/stores/authStore'
import { LIVENESS_BASE_URL } from '@/lib/config'
import ConfirmDialog, { useConfirmDialog } from "@/components/ui/confirm-dialog"

interface User {
  id: string
  email: string
  username: string
  role: string
  created_at: string
  has_face: boolean
}

export default function AdminSettingsPage() {
  const router = useRouter()
  const [users, setUsers] = useState<User[]>([])
  const [editingUser, setEditingUser] = useState<string | null>(null)
  const [editForm, setEditForm] = useState({ role: '' })
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoggingOut, setIsLoggingOut] = useState(false)
  const { isOpen: isConfirmOpen, showConfirm, hideConfirm, handleConfirm } = useConfirmDialog()

  // 检查管理员权限
  useEffect(() => {
    const { token, user, isAuthenticated } = useAuthStore.getState()
    
    if (!isAuthenticated()) {
      router.push('/login')
      return
    }
    
    if (!user || user.role !== 'admin') {
      router.push('/dashboard')
      return
    }
    
    setCurrentUser(user)
    loadUsers()
  }, [router])

  const loadUsers = async () => {
    try {
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/admin/users`)
      
      if (response.ok) {
        const result = await response.json()
        setUsers(result.users || [])
      }
    } catch (err) {
      console.error('加载用户列表失败:', err)
    }
  }

  const handleEditRole = (user: User) => {
    setEditingUser(user.id)
    setEditForm({ role: user.role })
  }

  const handleSaveRole = async (userId: string) => {
    setIsLoading(true)
    setError('')
    setSuccess('')

    try {
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/admin/users/${userId}/role`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ role: editForm.role })
      })

      const result = await response.json()

      if (response.ok && result.success) {
        setSuccess('用户角色更新成功')
        setEditingUser(null)
        loadUsers()
      } else {
        setError(result.message || '更新角色失败')
      }
    } catch (err) {
      setError('网络错误，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const handleDeleteUser = async (userId: string, username: string) => {
    showConfirm({
      title: '删除用户',
      message: `确定要删除用户 "${username}" 吗？此操作不可恢复，删除后该用户的所有数据将被清除。`,
      confirmText: '删除用户',
      cancelText: '取消',
      type: 'danger',
      onConfirm: async () => {
        setIsLoading(true)
        setError('')
        setSuccess('')

        try {
          const endpoint = LIVENESS_BASE_URL
          const response = await fetch(`${endpoint}/v1/admin/users/${userId}`, {
            method: 'DELETE'
          })

          const result = await response.json()

          if (response.ok && result.success) {
            setSuccess('用户删除成功')
            loadUsers()
          } else {
            setError(result.message || '删除用户失败')
          }
        } catch (err) {
          setError('网络错误，请稍后重试')
        } finally {
          setIsLoading(false)
        }
      }
    })
  }

  const handleCancelEdit = () => {
    setEditingUser(null)
    setEditForm({ role: '' })
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-4 sm:p-6 lg:p-8">
      <div className="max-w-6xl mx-auto">
        {/* 页面标题 */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
              管理员设置
            </h1>
            <p className="text-sm sm:text-base text-gray-600 dark:text-gray-400 mt-1">
              管理系统用户权限和账号设置
            </p>
          </div>
          <div className="flex gap-2 mt-4 sm:mt-0">
            <Button
              onClick={() => router.push('/admin/users')}
              variant="outline"
            >
              用户管理
            </Button>
            <Button
              onClick={() => router.push('/dashboard')}
              className="bg-blue-600 hover:bg-blue-700 text-white"
            >
              返回仪表板
            </Button>
          </div>
        </div>

        {/* 错误和成功提示 */}
        {error && (
          <Alert variant="destructive" className="mb-6">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}
        
        {success && (
          <Alert className="mb-6 border-green-200 bg-green-50 dark:bg-green-900/20">
            <AlertDescription className="text-green-700 dark:text-green-300">
              {success}
            </AlertDescription>
          </Alert>
        )}

        {/* 当前用户信息 */}
        {currentUser && (
          <Card className="mb-6">
            <CardHeader>
              <CardTitle className="flex items-center justify-center gap-2">
                <IconUser className="w-5 h-5" />
                当前登录信息
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
                <table className="w-full table-auto border-collapse">
                  <thead className="bg-gray-50 dark:bg-gray-800">
                    <tr className="border-b border-gray-200 dark:border-gray-700">
                      <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">用户名</th>
                      <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">角色</th>
                      <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                      <td className="p-4 text-center font-medium text-gray-900 dark:text-gray-100">{currentUser.username}</td>
                      <td className="p-4 text-center">
                        <div className="flex justify-center">
                          <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900/20 dark:text-purple-300">
                            <IconShield className="w-3 h-3 mr-1" />
                            管理员
                          </span>
                        </div>
                      </td>
                      <td className="p-4 text-center">
                        <Button 
                          size="sm" 
                          variant="outline"
                          onClick={() => {
                            if (isLoggingOut) return
                            showConfirm({
                              title: '退出登录',
                              message: '确定要退出当前账号吗？退出后需要重新登录。',
                              confirmText: '退出登录',
                              cancelText: '取消',
                              type: 'warning',
                              onConfirm: () => {
                                setIsLoggingOut(true)
                                useAuthStore.getState().logout()
                                router.push('/login')
                              }
                            })
                          }}
                          disabled={isLoggingOut}
                          className="hover:bg-red-50 hover:border-red-300 hover:text-red-700"
                        >
                          {isLoggingOut ? '退出中...' : '退出登录'}
                        </Button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 用户权限管理 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-center gap-2">
              <IconSettings className="w-5 h-5" />
              用户权限管理
            </CardTitle>
            <CardDescription className="text-center">
              管理系统中所有用户的角色和权限设置
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
              <table className="w-full table-auto border-collapse">
                <thead className="bg-gray-50 dark:bg-gray-800">
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">用户名</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">邮箱</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">当前角色</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">人脸状态</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">创建时间</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {users.map((user) => (
                    <tr key={user.id} className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                      <td className="p-4 text-center text-gray-900 dark:text-gray-100 font-medium">{user.username}</td>
                      <td className="p-4 text-center text-gray-600 dark:text-gray-400">{user.email}</td>
                      <td className="p-4 text-center">
                        {editingUser === user.id ? (
                          <div className="flex justify-center">
                            <select
                              value={editForm.role}
                              onChange={(e) => setEditForm({ role: e.target.value })}
                              className="text-sm px-2 py-1 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800"
                            >
                              <option value="user">普通用户</option>
                              <option value="admin">管理员</option>
                            </select>
                          </div>
                        ) : (
                          <div className="flex justify-center">
                            <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${
                              user.role === 'admin' 
                                ? 'bg-purple-100 text-purple-800 dark:bg-purple-900/20 dark:text-purple-300'
                                : 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300'
                            }`}>
                              <IconShield className="w-3 h-3 mr-1" />
                              {user.role === 'admin' ? '管理员' : '普通用户'}
                            </span>
                          </div>
                        )}
                      </td>
                      <td className="p-4 text-center">
                        <div className="flex justify-center">
                          <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${
                            user.has_face 
                              ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300'
                              : 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-300'
                          }`}>
                            {user.has_face ? '已录入' : '未录入'}
                          </span>
                        </div>
                      </td>
                      <td className="p-4 text-center text-gray-600 dark:text-gray-400 text-sm">
                        {new Date(user.created_at).toLocaleDateString()}
                      </td>
                      <td className="p-4 text-center">
                        {editingUser === user.id ? (
                          <div className="flex justify-center gap-1">
                            <Button
                              size="sm"
                              onClick={() => handleSaveRole(user.id)}
                              disabled={isLoading}
                              className="bg-green-600 hover:bg-green-700 text-white"
                            >
                              <IconCheck className="w-3 h-3" />
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={handleCancelEdit}
                              disabled={isLoading}
                            >
                              <IconX className="w-3 h-3" />
                            </Button>
                          </div>
                        ) : (
                          <div className="flex justify-center gap-1">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleEditRole(user)}
                              disabled={isLoading || user.username === currentUser?.username}
                              title={user.username === currentUser?.username ? '不能编辑自己的角色' : '编辑角色'}
                            >
                              <IconEdit className="w-3 h-3" />
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleDeleteUser(user.id, user.username)}
                              disabled={isLoading || user.username === currentUser?.username}
                              title={user.username === currentUser?.username ? '不能删除自己的账号' : '删除用户'}
                              className="text-red-600 hover:text-red-700 hover:bg-red-50"
                            >
                              <IconTrash className="w-3 h-3" />
                            </Button>
                          </div>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              
              {users.length === 0 && (
                <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                  暂无用户数据
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 确认弹窗 */}
      <ConfirmDialog
        isOpen={isConfirmOpen}
        title="退出登录"
        message="确定要退出当前账号吗？退出后需要重新登录。"
        confirmText="退出登录"
        cancelText="取消"
        type="warning"
        onConfirm={handleConfirm}
        onCancel={hideConfirm}
      />
    </div>
  )
}

